<template>
  <section>
    <van-sticky>
      <PageHeader title="我的服务"/>
    </van-sticky>

    <div class="bg-color-white pd10" v-if="servicePackage">
      <div class="text-left font-biger strong">服务套餐：{{servicePackage.name}}</div>
      <div class="text-left font-common strong mt10">服务内容：</div>
      <div class="text-left font-common color-gray-dark mt10" v-html="servicePackage.detail"></div>
    </div>

    <div class="flex flex-col mt10 bg-color-white font-common" v-if="order">
      <div class="flex flex-row flex-left pd10">订单号：{{order.order_sn}}<span class="ml10"><van-button round size="mini" type="primary" @click="onCopy(order.order_sn)">复制</van-button></span></div>
      <div class="flex flex-row flex-left pd10">费用：{{order.order_money}}元</div>
      <div class="flex flex-row pd10">
        <div class="flex flex-row flex-left flex-1">订单状态：{{order.order_status_label}}</div>
        <div class="flex flex-row flex-left flex-1">付款状态：{{order.pay_status_label}}</div>
      </div>
      <div class="flex flex-row flex-left pd10">下单时间：{{order.create_time|timeFormat('yyyy-MM-dd hh:mm:ss')}}</div>
      <div class="flex flex-row flex-left pd10" v-if="order.pay_time > 0">付款时间：{{order.pay_time|timeFormat('yyyy-MM-dd hh:mm:ss')}}</div>
      <div class="flex flex-row flex-left pd10" v-if="order.pay_time > 0">服务期限：{{order.service_begin_time|timeFormat('yyyy-MM-dd hh:mm:ss')}} 至 {{order.service_end_time|timeFormat('yyyy-MM-dd hh:mm:ss')}}</div>
    </div>

    <div class="empty-box"></div>

    <div class="bg-color-white pd10 bottom-wrapper text-right" v-if="order">
      <van-button round
                  size="small"
                  type="primary"
                  class="mr10"
                  @click="servicePopupVisible=true">联系客服</van-button>

      <van-button round
                  size="small"
                  plain
                  type="info"
                  class="mr10"
                  @click="cancel"
                  v-if="order.order_status == SERVICE_PACKAGE_ORDER_STATUS_CONFIRMED && order.pay_status==SERVICE_PACKAGE_ORDER_PAY_STATUS_UNPAIED">取消订单</van-button>
      <van-button round
                  size="small"
                  type="danger"
                  @click="chooseWXPay"
                  v-if="order.order_status == SERVICE_PACKAGE_ORDER_STATUS_CONFIRMED && order.pay_status==SERVICE_PACKAGE_ORDER_PAY_STATUS_UNPAIED">立即付款</van-button>
    </div>

    <van-popup v-model="servicePopupVisible" :style="{ width: '60%' }">
      <div class="text-center mt10">
        摩西客服
      </div>

      <div class="text-center mt10">
        <img :src="STATIC_BASE_URL + 'images/mp/service-wx.jpg'" height="200" width="200"/>
      </div>

      <div class="text-center mt5 mb20 font-big">
        长按二维码添加客服
      </div>
    </van-popup>
  </section>
</template>

<script>
  import PageHeader from "../../componets/PageHeader";
  import Vue from 'vue';
  import {Sticky, Popup, Toast, Button, Dialog} from 'vant';
  import {
    servicePackageOrderCancelUri,
    servicePackageOrderDetailUri,
    STATIC_BASE_URL,
    wechatJsApiConfigUri,
    wxPayCreateCourseOrderPayTradeUri, wxPayCreateServicePackageOrderPayTradeUri, wxPayQueryUri
  } from "../../../common/api";
  import {
    SERVICE_PACKAGE_ORDER_PAY_STATUS_PAIED,
    SERVICE_PACKAGE_ORDER_PAY_STATUS_UNPAIED,
    SERVICE_PACKAGE_ORDER_STATUS_CONFIRMED
  } from "../../../common/constants";

  Vue.use(Sticky).use(Popup).use(Toast).use(Button);

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        SERVICE_PACKAGE_ORDER_STATUS_CONFIRMED: SERVICE_PACKAGE_ORDER_STATUS_CONFIRMED,
        SERVICE_PACKAGE_ORDER_PAY_STATUS_UNPAIED: SERVICE_PACKAGE_ORDER_PAY_STATUS_UNPAIED,
        SERVICE_PACKAGE_ORDER_PAY_STATUS_PAIED: SERVICE_PACKAGE_ORDER_PAY_STATUS_PAIED,
        STATIC_BASE_URL: STATIC_BASE_URL,
        servicePackage: null,
        order: null,
        servicePopupVisible: false,
        chargeOverlayVisible: false
      }
    },
    methods: {
      onCopy(text) {
        this.$copyText(text).then(
          res => {
            Toast('复制成功');
          },
          err => {
            Toast("复制失败");
          }
        )
      },
      getInfo() {
        const that = this;
        this.$http.get(servicePackageOrderDetailUri + '?order_sn=' + this.$route.query.order_sn).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            that.servicePackage = data.package;
            that.order = data.order;
          }
        }, response => {
          // error callback
        })
      },
      getJsApiConfig() {
        if(!isWxServiceEnable) {
          return;
        }
        const that = this;
        const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.appId, // 必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature,// 必填，签名
              jsApiList: ['hideAllNonBaseMenuItem', 'chooseWXPay'] // 必填，需要使用的JS接口列表
            });

            wx.ready(function () {
              console.log('wx配置成功');
              wx.hideAllNonBaseMenuItem();
            });

            wx.error(function (res) {
              console.log('wx配置出错');
            });
          }
        }, response => {
          // error callback
        })
      },
      chooseWXPay() {
        const orderSn = this.order.order_sn;
        const that = this;
        const url = wxPayCreateServicePackageOrderPayTradeUri + '?order_sn=' + orderSn;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            const payParams = JSON.parse(data.pay_params);
            wx.chooseWXPay({
              timestamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: function (res) {
                // 支付成功后的回调函数
                Toast('付款成功');
                that.onPaied(orderSn, data.pay_trade_no);
              },
              fail: function (res) {
                Toast('支付失败');
              }
            });
          }
        }, response => {
          // error callback
        });
      },
      onPaied(orderSn, payTradeNo) {
        const that = this;
        const url = wxPayQueryUri + '?pay_trade_no=' + payTradeNo;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            if (data.success == 1) {
              that.getInfo();
            } else {
              Toast.fail('支付出错，请重试或联系客服付款');
            }
          }
        }, response => {
          // error callback
        })
      },
      cancel() {
        const that = this;
        Dialog.confirm({
          message: '确定要取消吗？',
        }).then(() => {
          const url = servicePackageOrderCancelUri + '?order_sn=' + this.$route.query.order_sn;
          that.$http.get(url).then(response => {
            let {code, msg, data} = response.body
            if (code != 0) {
              Toast.fail(msg);
            } else {
              that.getInfo();
            }
          }, response => {
            // error callback
          })
        }).catch(() => {
          // on cancel
        });
      },
    },
    created: function () {
      let _href = window.location.href;
      if (isWxServiceEnable && _href.indexOf('&replace=1') <= -1) {
        window.location.replace(_href + '&replace=1');
      }
    },
    mounted: function () {
      if (this.GLOBAL.userInfo) {
        this.getInfo();
      }
      this.EventBus.$on('OnUserLogined', () => {
        this.getInfo();
      });
      this.getJsApiConfig();
    }
  }
</script>

<style scoped>
  .empty-box {
    height: calc(50px + env(safe-area-inset-bottom));
  }

  .bottom-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding-bottom: calc(10px + env(safe-area-inset-bottom));
  }

  .bottom-wrapper .item {
    height: 50px;
  }

  .bottom-wrapper .item .iconfont {
    font-size: 20px;
  }
</style>
